<?php
declare (strict_types = 1);
namespace app\admin\controller;

use think\Request;
use think\facade\{View};
use think\exception\ValidateException;

use app\common\model\{FinancialRecord, User};
use app\common\validate\{FinancialRecordValidate};

/** 财务管理 */
class FinancialController extends BaseController
{
    private $finModel;
    public function __construct(FinancialRecord $finModel)
    {
        parent::initialize();
        $this->finModel = $finModel;
    }

    /** 渲染财务列表页面 */
    public function financial_list()
    {
        return view();
    }

    /** 提现数据列表 */
    public function financial_data()
    {
        $data = input('');

        try{
            validate(FinancialRecordValidate::class)->scene('list')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $userModel = new User();

        $where = [];

        /** 搜索条件 */
        if($data && isset($data['key'])){
            if(!empty($data['key']['nickname'])){
                $userIds = $userModel->getCol([['nickname', 'like', '%' . $data['key']['nickname'] . '%']], 'id')['data'];
                
                $where[] = [['user_id', 'in', $userIds]];
            }

            if(!empty($data['key']['content'])){
                $where[] = [['content', 'like', '%' . $data['key']['content'] . '%']];
            }
        }

        /** 查询数据总条数 */
        $count = $this->finModel->getNum($where)['data'];

        /** 查询列表 */
        $list = $this->finModel->getList($where, 1, $data['page'], $data['limit'], '*', 'id DESC');

        if($list['code'] != 'ok'){
            $this->error_back('暂无数据~');
        }

        foreach($list['data'] as &$v){
            $v['nickname'] = $userModel->getVal(['id' => $v['user_id']], 'nickname')['data'];
        }

        $this->success_back('ok', $list['data'], $count);
    }

    /**
     * 删除
     */
    public function financial_del()
    {
        $data = input('post.');

        try{
            validate(FinancialRecordValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $flag = $this->finModel::destroy($data['id']);

        if(!$flag){
            $this->error_back('删除失败');
        }

        $this->success_back('删除成功');
    }
}
